package com.example.elm.Login;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.elm.Email.SendEmail;
import com.example.elm.First_Page.First_Page;
import com.example.elm.R;
import com.example.elm.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Input_SMS_Code_Page extends AppCompatActivity {

    EditText sms_code_1, sms_code_2, sms_code_3, sms_code_4, sms_code_5, sms_code_6;
    TextView email_text, sms_is_current, how_many_s;

    List<EditText> sms_code = new ArrayList<>();
    String email, sms, name, auto_name;
    boolean is_upload_data = false, user_is_in_data = false;;
    AlertDialog dialog;

    private class Upload_User_Data_Thread extends Thread {
        @Override
        public void run() {
            is_upload_data = false;
            user_is_in_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM user WHERE email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        user_is_in_data = true;
                        String sql2 = "update `elm`.`user` set android_id = ? WHERE email = ?;";
                        preparedStatement = connection.prepareStatement(sql2);
                        preparedStatement.setString(1, Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
                        preparedStatement.setString(2, email);
                        preparedStatement.executeUpdate();
                    }

                    if (!user_is_in_data) {
                        String sql2 = "INSERT INTO `elm`.`user`(email, user_name, android_id) VALUES (?, ?, ?);";
                        preparedStatement = connection.prepareStatement(sql2);
                        preparedStatement.setString(1, email);
                        preparedStatement.setString(2, auto_name);
                        preparedStatement.setString(3, Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
                        preparedStatement.executeUpdate();

                        String sql3 = "CREATE TABLE `elm`.`" + email + "_user_location` " +
                                "(id INT PRIMARY KEY AUTO_INCREMENT," +
                                " address VARCHAR(255)," +
                                " door_number VARCHAR(255), label VARCHAR(45)," +
                                " name VARCHAR(255), phone_number VARCHAR(255), lat DOUBLE, lng DOUBLE, is_sir TINYINT, city VARCHAR(45), district VARCHAR(45), province VARCHAR(45));";
                        preparedStatement = connection.prepareStatement(sql3);
                        preparedStatement.executeUpdate();

                        String sql4 = "CREATE TABLE `elm`.`" + email + "_user_order` " +
                                "(id INT PRIMARY KEY AUTO_INCREMENT," +
                                " shop_name VARCHAR(255), order_state INT, order_address VARCHAR(255), tableware INT, delivery_rider_name VARCHAR(255), is_phone_number_protection INT, order_number MEDIUMTEXT, order_time VARCHAR(255), payment_methods INT, product_data LONGTEXT, packing_fee DOUBLE, delivery_fee DOUBLE, use_red_envelope MEDIUMTEXT, actual_payment DOUBLE, shop_email VARCHAR(45), discount_how_many DOUBLE, how_many_km DOUBLE, note VARCHAR(255));";
                        preparedStatement = connection.prepareStatement(sql4);
                        preparedStatement.executeUpdate();
                    }
                    is_upload_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_upload_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();

                    Intent intent = new Intent(Input_SMS_Code_Page.this, First_Page.class);
                    startActivity(intent);
                }
            });
        }
    }

    private class Time_Thread extends Thread {
        @Override
        public void run() {
            for (int i = 60; i >= 0; i--) {
                int finalI = i;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        how_many_s.setText("重新获取(" + finalI + "s)");
                        if (finalI == 0) {
                            how_many_s.setText("重新获取");
                            how_many_s.setTextColor(Color.BLACK);
                            how_many_s.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    sms = sms_code();
                                    how_many_s.setTextColor(Color.rgb(128, 128, 128));
                                    new SendEmail(email, sms, "饿了没", "【饿了没】"+ sms + "（登录验证码，请完成验证），如非本人操作，请忽略本短信。").sendemail();
                                    Toast.makeText(Input_SMS_Code_Page.this, "已重新发送验证码", Toast.LENGTH_SHORT).show();
                                    Time_Thread timeThread = new Time_Thread();
                                    timeThread.start();
                                }
                            });
                        }
                    }
                });

                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_sms_code_page);

        email = getIntent().getStringExtra("email");
        sms = getIntent().getStringExtra("sms");

        sms_code_1 = findViewById(R.id.sms_code_1);
        sms_code_2 = findViewById(R.id.sms_code_2);
        sms_code_3 = findViewById(R.id.sms_code_3);
        sms_code_4 = findViewById(R.id.sms_code_4);
        sms_code_5 = findViewById(R.id.sms_code_5);
        sms_code_6 = findViewById(R.id.sms_code_6);
        email_text = findViewById(R.id.email_text);
        sms_is_current = findViewById(R.id.sms_is_current);
        how_many_s = findViewById(R.id.how_many_s);

        Time_Thread timeThread = new Time_Thread();
        timeThread.start();

        email_text.setText("验证码已发送至 " + email);

        sms_code.add(sms_code_1);
        sms_code.add(sms_code_2);
        sms_code.add(sms_code_3);
        sms_code.add(sms_code_4);
        sms_code.add(sms_code_5);
        sms_code.add(sms_code_6);

        sms_code_1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!sms_code_1.getText().toString().isEmpty()) {
                    sms_code_2.setEnabled(true);
                    sms_code_2.requestFocus();
                    sms_code_1.setEnabled(false);
                }
            }
        });

        sms_code_2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!sms_code_2.getText().toString().isEmpty()) {
                    sms_code_3.setEnabled(true);
                    sms_code_3.requestFocus();
                    sms_code_2.setEnabled(false);
                }
            }
        });

        sms_code_2.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DEL) {
                    sms_code_2.setText("");
                    sms_code_1.setEnabled(true);
                    sms_code_1.setText("");
                    sms_code_1.requestFocus();
                    sms_code_2.setEnabled(false);
                }
                return true;
            }
        });

        sms_code_3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!sms_code_3.getText().toString().isEmpty()) {
                    sms_code_4.setEnabled(true);
                    sms_code_4.requestFocus();
                    sms_code_3.setEnabled(false);
                }
            }
        });

        sms_code_3.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DEL) {
                    sms_code_3.setText("");
                    sms_code_2.setEnabled(true);
                    sms_code_2.setText("");
                    sms_code_2.requestFocus();
                    sms_code_3.setEnabled(false);
                }
                return true;
            }
        });

        sms_code_4.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!sms_code_4.getText().toString().isEmpty()) {
                    sms_code_5.setEnabled(true);
                    sms_code_5.requestFocus();
                    sms_code_4.setEnabled(false);
                }
            }
        });

        sms_code_4.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DEL) {
                    sms_code_4.setText("");
                    sms_code_3.setEnabled(true);
                    sms_code_3.setText("");
                    sms_code_3.requestFocus();
                    sms_code_4.setEnabled(false);
                }
                return true;
            }
        });

        sms_code_5.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!sms_code_5.getText().toString().isEmpty()) {
                    sms_code_6.setEnabled(true);
                    sms_code_6.requestFocus();
                    sms_code_5.setEnabled(false);
                }
            }
        });

        sms_code_5.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DEL) {
                    sms_code_5.setText("");
                    sms_code_4.setEnabled(true);
                    sms_code_4.setText("");
                    sms_code_4.requestFocus();
                    sms_code_5.setEnabled(false);
                }
                return true;
            }
        });

        sms_code_6.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!sms_code_6.getText().toString().isEmpty()) {
                    String user_input_sms = sms_code_1.getText().toString() + sms_code_2.getText().toString() + sms_code_3.getText().toString() + sms_code_4.getText().toString() + sms_code_5.getText().toString() + sms_code_6.getText().toString();
                    if (user_input_sms.equals(sms)) {
                        set_dialog();
                        auto_name = create_user_name();

                        Upload_User_Data_Thread uploadUserDataThread = new Upload_User_Data_Thread();
                        uploadUserDataThread.start();
                    }
                    else {
                        sms_is_current.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        sms_code_6.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_DEL) {
                    sms_code_6.setText("");
                    sms_code_5.setEnabled(true);
                    sms_code_5.setText("");
                    sms_code_5.requestFocus();
                    sms_code_6.setEnabled(false);
                }
                return true;
            }
        });
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    public String sms_code() {
        String ans = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            ans += String.valueOf(random.nextInt(9));
        }
        System.out.println(ans);
        return ans;
    }

    public String create_user_name() {
        name = "";
        int how_long = new Random().nextInt(4) + 8;

        Character[] random_text = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '_'};
        for (int i = 0; i < how_long; i++) {
            int num = new Random().nextInt(62);
            name += random_text[num];
        }

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            try {
                Connection_SQL user_sql = new Connection_SQL();
                Connection connection = user_sql.connection();
                String sql = "SELECT * FROM user WHERE user_name = ?;";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, name);
                ResultSet set = preparedStatement.executeQuery();
                while (set.next()) {
                    if (set.getString("user_name").equals(name)) {
                        create_user_name();
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return name;
    }
}